package com.commerce.weather.Sevice;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.commerce.weather.Entity.DataWeather;
import com.commerce.weather.R;
import com.commerce.weather.utils.CallLocation;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, Intent intent) {
        SharedPreferences sp = context.getSharedPreferences("sign", context.MODE_PRIVATE);
        final String s = sp.getString("city", "北京");
        Call call = new CallLocation().location(s, context);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String string = response.body().string();
                Log.d("TAG", "onResponse: " + string);
                Gson gson = new Gson();
                DataWeather.ResultBean.RealtimeBean realtime = gson.fromJson(string, DataWeather.class).getResult().getRealtime();
                NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "CHANNELID");
                builder.setAutoCancel(true)
                        .setSmallIcon(R.drawable.logo)
                        .setSubText("天气通知")
                        .setWhen(System.currentTimeMillis())
                        .setContentTitle(s)
                        .setContentText(realtime.getInfo()+"/"+realtime.getTemperature()+"°C");
                //获取通知管理器
                NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                //设置渠道
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    NotificationChannel channel = new NotificationChannel("1", "channel3", NotificationManager.IMPORTANCE_DEFAULT);
                    channel.enableLights(true);
                    channel.setLightColor(Color.green(1));
                    channel.setShowBadge(true);
                    manager.createNotificationChannel(channel);
                    builder.setChannelId("1");
                }
                manager.notify(1, builder.build());
            }
        });
    }
}
